<template>
  <div>
    <a-row :gutter="12">
      <a-col :md="4" :sm="24" :lg="4">
        <a-card
          :bordered="false"
          :loading="treeLoading"
          :bodyStyle="{ padding: '0px 10px' }"
          style="overflow: auto; min-height: 390px"
        >
          <div v-if="this.treeData != ''">
            <a-tree
              :treeData="treeData"
              v-if="treeData.length"
              @select="(e) => handleClick(e,'one')"
              :defaultExpandAll="false"
              :replace-fields="replaceFields"
              :defaultExpandedKeys="defaultExpandedKeys"
            >
              <template #title="{ key: treeKey, name }">
                <a-dropdown :trigger="['contextmenu']">
                  <span>{{ name }}</span>
                  <template #overlay>
                    <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey)">
                      <a-menu-item key="1" @click="editClass"><a-icon type="edit" />编辑</a-menu-item>
                      <a-menu-item key="2" @click="deleteClass"><a-icon type="delete" />删除</a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </a-tree>
          </div>
          <div v-else>
            <a-empty :image="simpleImage" />
          </div>
        </a-card>
      </a-col>
      <a-col :md="20" :sm="24" :lg="20">
        <x-card v-if="hasPerm('sysUser:page')">
          <div slot="content" class="table-page-search-wrapper">
            <a-form layout="inline">
              <!-- <a-row :gutter="48">
                <a-col :md="6" :sm="6">
                  <a-form-item label="产品编码">
                    <a-input v-model="queryParam.code" allow-clear placeholder="请输入产品编码" />
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="6">
                  <a-form-item label="产品名称">
                    <a-input v-model="queryParam.name" allow-clear placeholder="请输入产品名称" />
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="6">
                  <a-form-item label="拼音码">
                    <a-input v-model="queryParam.pyCode" allow-clear placeholder="请输入拼音码"></a-input>
                  </a-form-item>
                </a-col> 
                <a-col :md="6" :sm="6">
                  <a-button type="primary" @click="search">查询</a-button> 
                </a-col>
              </a-row> -->

              <a-row :gutter="48">
                <a-col :md="5" :sm="24" class="number-input-box" style="padding-right: 0">
                  <a-form-item label="名称">
                    <a-input v-model.trim="queryParam.name" allow-clear placeholder="项目名称/拼音码" @keydown.enter="search"></a-input>
                    <!-- <a-input v-model="queryParam.searchValue" allow-clear placeholder="请输入项目名称" /> -->
                  </a-form-item>
                </a-col>

                <a-col :md="5" :sm="24">
                  <a-form-item label="启用状态">
                    <!-- <a-switch @change="isDisabledChange" />  -->
                    <a-select @change="isDisabledChange" allowClear placeholder="请选择" v-model="queryParam.isDisabled">
                      <a-select-option :value="undefined">
                        <div>请选择</div>
                      </a-select-option>
                      <a-select-option :value="0">
                        <div>已启用</div>
                      </a-select-option>
                      <a-select-option :value="1">
                        <div>未启用</div>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="5" :sm="24" style="padding-right: 0; padding-left: 0">
                  <a-form-item label="核算业绩">
                    <!-- <a-switch @change="isCalculateChange" />  -->
                    <a-select @change="isCalculateChange" allowClear placeholder="请选择" v-model="queryParam.isAchieve">
                      <a-select-option :value="undefined">
                        <div>请选择</div>
                      </a-select-option>
                      <a-select-option :value="0">
                        <div>否</div>
                      </a-select-option>
                      <a-select-option :value="1">
                        <div>是</div>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24" style="padding-right: 0">
                  <!-- <a-button type="primary" @click="$refs.table.refresh(true)">1查询</a-button>  this.$refs.table.refresh只是一个刷新方法-->
                  <a-button type="primary" @click="search">查询</a-button>
                  <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                </a-col>
              </a-row>
              <a-row :gutter="48">
                <a-col :md="6" :sm="24" style="padding-right: 0">
                  <a-form-item label="耗材名称">
                    <a-input
                      v-model.trim="queryParam.consumableName"
                      allow-clear
                      placeholder="请输入耗材名称"
                      @keydown.enter="search"
                    ></a-input>
                  </a-form-item>
                </a-col>

                <a-col :md="9" :sm="24" style="padding-right: 0">
                  <a-form-item label="价格区间">
                    <a-input-number
                      :min="1" 
                      :default-value="0"
                      :value="queryParam.minPrice"
                      :formatter="(value) => `${value}`"
                      :parser="(value) => value.replace(/\$\s?|(,*)/g, '')" 
                       
                      @change="value => {  
                        if(!isNumber(value)){
                          this.queryParam.minPrice = undefined
                        }else{
                          this.queryParam.minPrice = Number(value)
                          this.queryParam = Object.assign({},this.queryParam)
                        } 
                      }" 
                      

                    />
                    -
                    <a-input-number
                      :default-value="0"
                      :value="queryParam.maxPrice"
                      :min="queryParam.minPrice" 
                      :formatter="(value) => `${value}`"
                      :parser="(value) => value.replace('%', '')" 
                      @change="value => {  
                        if(!isNumber(value)){
                          this.queryParam.maxPrice = undefined
                        }else{
                          this.queryParam.maxPrice = Number(value)
                          this.queryParam = Object.assign({},this.queryParam)
                        } 
                      }" 
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </x-card>
        <a-card :bordered="false">
          <div style="position: absolute; top: 10px; left: 24px">
            <!-- <a-button icon="plus-circle" type="primary" @click="addClass">新增产品类别</a-button> -->
            <a-button icon="plus-circle" type="primary" @click="addProject">新增产品</a-button>
            <!-- <x-down ref="batchExport" @batchExport="batchExport"></x-down> -->
          </div>
          <super-table
            ls_props_columns="projectManage_table"
            :scroll="{ x: 1000 }"
            ref="table"
            :pageSize="20"
            :columns="columns"
            :data="loadData"
            :rowKey="(record) => record.id"
          >
            <template slot="isAchieve" slot-scope="tags">
              <a-tag :color="tags==true || tags == '1' ? 'red' : 'green' ">
                {{ tags==true || tags == '1'?'是':'否' }}
              </a-tag>
            </template>
            <template slot="isDisabled" slot-scope="tags">
              <a-tag :color="tags==true || tags == '1' ? '#d9d9d9' : '#39f' ">
                {{ tags==true || tags == '1'?'未启用':'已启用' }}
              </a-tag>
            </template>
            <!--名称-->
            <template slot="name" slot-scope="text">
              <a-tooltip>
                <template slot="title">
                  {{ text }}
                </template>
                {{ text }}
              </a-tooltip>
            </template>
            <!--打印名称-->
            <template slot="printName" slot-scope="text">
              <a-tooltip>
                <template slot="title">
                  {{ text }}
                </template>
                {{ text }}
              </a-tooltip>
            </template>
            <!--手术名称-->
            <template slot="operateName" slot-scope="text">
              <a-tooltip>
                <template slot="title">
                  {{ text }}
                </template>
                {{ text }}
              </a-tooltip>
            </template>
            <!--操作-->
            <template slot="action" slot-scope="text, record">
              <div class="g-flex g-y-center">
                <a-button type="link" @click="editProject(record)">修改</a-button>
                <!-- <a-button type="link" @click="copyProject(record)">复制</a-button> -->
              </div>
            </template>
          </super-table>
        </a-card>
      </a-col>
    </a-row>
    <add-project
      ref="addProject"
      @search="search"
      :modal_type="modal_type"
      :row_record="current_row_record"
    ></add-project>
    <add-class ref="addclass" :modal_type="modal_type" :row_record="current_row_record"></add-class>
  </div>
</template>
<script>
import { getProduct, getItemDetailById, getProductList } from '@/api/bd/product'
import { SuperTable, XCard, XDown } from '@/components'
import { Empty } from 'ant-design-vue'
import { sysUserChangeStatus, sysUserExport } from '@/api/modular/system/userManage'
import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'
// import { getItemClasssify, getItemDetailById } from '@/api/modular/main/customer/customerScene'
import addProject from '@/views/baseData/projectManage/product/addProject.vue'
import addClass from '@/views/baseData/projectManage/product/addClase.vue'
export default {
  components: {
    XDown,
    XCard,
    SuperTable,
    addProject,
    addClass,
  },
  data() {
    return {
      db: [{}],
      modal_type: 'add',
      current_row_record: {},
      // 查询参数
      // 查询参数
      queryParam: {
        code: '',
        name: '',
        pycode: '',
        // searchValue: '',
        pageNum: 1, //第几页
        pageSize: 10, //每页中显示数据的条数
        id: undefined,

        consumableName: '', // 耗材
        minPrice: undefined, // 价格区间
        maxPrice: undefined, // 价格区间
        isDisabled: undefined, // 是否禁用
        isAchieve: undefined, // 是否核算业绩
      },
      pagination: {
        current: 1, //当前页
        pageSize: 20, //当前页数
        total: 0, //总条数
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30'], //这里注意只能是字符串，不能是数字
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
      // 表头
      columns: [
        {
          title: '核算业绩',
          align: 'center',
          dataIndex: 'isAchieve',
          width: 100,
          // customRender: (isAchieve) => {
          //   return isAchieve === '1' ? '是' : '否'
          // },
          scopedSlots: { customRender: 'isAchieve' },
        },
        {
          title: '启用状态',
          align: 'center',
          dataIndex: 'isDisabled',
          width: 80,
          // customRender: (isDisabled) => {
          //   return isDisabled === '0' ? <span>否</span> : <span style="color:red">是</span>
          // },
          scopedSlots: { customRender: 'isDisabled' },
        },
        {
          title: '产品编码',
          align: 'center',
          dataIndex: 'code',
          width: 120, 
          customRender: (code) => {
            if (!code) {
              return '-'
            } else {
              return code
            }
          },
        },
        {
          title: '产品名称',
          align: 'center',
          dataIndex: 'name',
          width: 200,  
          ellipsis: true,
          customRender: (name) => {
            if (!name) {
              return '-'
            } else {
              return name
            }
          },
        },
        {
          title: '拼音码',
          align: 'center',
          dataIndex: 'pyCode',
          width: 120,
          customRender: (pyCode) => {
            if (!pyCode) {
              return '-'
            } else {
              return pyCode
            }
          },
        },
        
        
        
        
        
        {
          title: '产品类别',
          align: 'center', 
          dataIndex: 'prdtTypeName',
          width: 100,
          customRender: (prdtTypeName) => {
            if (!prdtTypeName) {
              return '-'
            } else {
              return prdtTypeName
            }
          },
        },
        {
          title: '单价',
          align: 'center',
          dataIndex: 'unitDefinitionPrice',
          width: 100,
          customRender: (unitDefinitionPrice) => {
            if (unitDefinitionPrice == '' || unitDefinitionPrice == null) {
              return '-'
            } else {
              return '¥' + unitDefinitionPrice
            }
          },
        },

        {
          title: '耗材',
          align: 'center',
          dataIndex: 'dictItemName',
          key: 'dictItemName',
          width: 120,
          customRender: (dictItemName) => {
            if (!dictItemName) {
              return '-'
            } else {
              return dictItemName
            }
          },
        },
        {
          title: '耗材数量',
          align: 'center',
          dataIndex: 'numberConsumable',
          key: 'numberConsumable',
          width: 80,
          customRender: (numberConsumable) => {
            return numberConsumable
          },
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'unitDefinitionSpec',
          key: 'unitDefinitionSpec',
          width: 120,
          customRender: (unitDefinitionSpec) => {
            return unitDefinitionSpec
          },
        },
        {
          title: '剂型',
          align: 'center',
          dataIndex: 'formulations',
          key: 'formulations',
          width: 120,
          customRender: (formulations) => {
            if (!formulations) {
              return '-'
            } else {
              return formulations
            }
          },
        },
        // {
        //   title: '剂量',
        //   align: 'center',
        //   dataIndex: 'dose',
        //   key: '',
        //   width: 80,
        //   customRender: (dose) => {
        //     if (!dose) {
        //       return '-'
        //     } else {
        //       return dose
        //     }
        //   },
        // },
        // {
        //   title: '安全剂量',
        //   align: 'center',
        //   dataIndex: 'saveDose',
        //   width: 100, 
        //   customRender: (saveDose) => {
        //     if (!saveDose) {
        //       return '-'
        //     } else {
        //       return saveDose
        //     }
        //   },
        // },
        { title: '操作',  align: 'center', scopedSlots: { customRender: 'action',width: 80 }, fixed: 'right', width: 80 },

        // { title: '项目编码', dataIndex: 'code', width: 120, fixed: 'left' },
        // { title: '一级类别', dataIndex: '1', width: 120, checked: false },
        // { title: '二级类别', dataIndex: '2', width: 120, checked: false },
        // { title: '三级类别', dataIndex: '3', width: 120, checked: false },
        // { title: '项目名称', dataIndex: 'name', width: 120, scopedSlots: { customRender: 'name' }, ellipsis: true },
        // { title: '核算成交', dataIndex: 'isAchieve', width: 100 },
        // { title: '核算业绩', dataIndex: 'isDeal', width: 100 },
        // { title: '是否需要执行', dataIndex: 'isExecute', width: 100 },
        // { title: '禁用', dataIndex: 'isDisabled', width: 100 },
        // { title: '次数', dataIndex: 'useTimes', width: 80 },
        // { title: '项目单位', dataIndex: 'basicUnit', width: 100 },
        // { title: '项目售价', dataIndex: 'price', width: 100 },
        // { title: '最低价', dataIndex: 'minPrice', width: 100 },
        // { title: '最高价', dataIndex: 'maxPrice', width: 100 },
        // { title: '执行科室', dataIndex: 'achieveDept', width: 100 },
        // { title: '业绩科室', dataIndex: 'execDept', width: 100 },
        // { title: '二级业绩科室', dataIndex: 'twoDeptName', width: 100 },
        // { title: '项目说明', dataIndex: 'modifier', width: 100 },
        // {
        //   title: '打印名称',
        //   dataIndex: 'printName',
        //   width: 100,
        //   scopedSlots: { customRender: 'printName' },
        //   ellipsis: true,
        // },
        // {
        //   title: '手术名称',
        //   dataIndex: 'operateName',
        //   width: 100,
        //   scopedSlots: { customRender: 'operateName' },
        //   ellipsis: true,
        // },
        // { title: '费用类别', dataIndex: 'royaltyRate', width: 100 },
        // { title: '医生分值', dataIndex: 'doctorScore', width: 100 },
        // { title: '护士分值', dataIndex: 'nurseScore', width: 100 },
        // { title: '编辑时间', dataIndex: 'recordDate', width: 100 },
        // { title: '操作', scopedSlots: { customRender: 'action' }, fixed: 'right', width: 120 },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        this.queryParam.pageNum = parameter.pageNum
        this.queryParam.pageSize = parameter.pageSize
        console.log(this.queryParam, parameter)
        return getItemDetailById(Object.assign(this.queryParam)).then((res) => {
          console.log(res, '右边表格')
          return res
        })
        // return getItemDetailById(Object.assign(parameter, this.queryParam)).then((res) => {
        //   console.log('右边表格', res)
        //   return res
        // })
      },
      tableData: [],
      treeData: [],
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      sexDictTypeDropDown: [],
      statusDictTypeDropDown: [],
      treeLoading: true,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      replaceFields: {
        title: 'name',
        key: 'id',
      },
      options: {
        alert: {
          show: true,
          clear: () => {
            this.selectedRowKeys = []
          },
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
        },
      },
      clickShowNav: false
    }
  },
  created() {
    this.getDB()
  },
  watch:{ 
    clickShowNav(){
      if(!this.clickShowNav){
        this.loadData = (parameter) => { 
          this.queryParam.current = parameter.pageNum
          this.queryParam.pageNum = parameter.pageNum
          this.queryParam.pageSize = parameter.pageSize
           
          return getProductList(Object.assign(this.queryParam, parameter)).then((res) => {  
            return res 
          })
        } 
      }else{
        this.loadData = (parameter) => { 
          this.queryParam = { 
            current: parameter.pageNum,
            pageNum: parameter.pageNum,
            pageSize: parameter.pageSize
          }  
          return getItemDetailById(Object.assign(this.queryParam, parameter)).then((res) => {  
            return res 
          })
        } 
      }
    }
  },
  methods: {
    isNumber(value) {         //验证是否为数字
      var patrn = /^(-)?\d+(\.\d+)?$/;
      if (patrn.exec(value) == null || value == "") {
          return false
      } else {
          return true
      }
    },
    // 查询条件的是否禁用
    isDisabledChange(value) {
      console.log(value)
      this.queryParam.isDisabled = value
    },
    // 查询条件是否核算业绩
    isCalculateChange(value) {
      this.queryParam.isAchieve = value
    },
    reset() {
      this.queryParam.pyCode = ''
      this.queryParam.name = ''
      this.queryParam.code = ''
      this.queryParam.consumableName = ''// 耗材
      this.queryParam.minPrice = undefined // 价格区间
      this.queryParam.maxPrice = undefined // 价格区间
      this.queryParam.isDisabled = undefined // 是否禁用
      this.queryParam.isAchieve = undefined // 是否核算业绩
      this.queryParam = Object.assign({},this.queryParam)
      // this.loadData = (parameter) => {
      //   return getProductList(Object.assign(this.queryParam, parameter)).then((res) => {
      //     console.log('右边表格', res, this.parameter, this.queryParam)
      //     return res
      //   })
      // }
      // this.$nextTick(() => { 
      //   this.$refs.table.refresh()
      // })
    },
    // search() {
    //   this.loadData = (parameter) => {
    //     console.log(parameter)
    //     return getProductList(this.queryParam, parameter).then((res) => {
    //       console.log(res)
    //       return res
    //     })
    //   }
    //   this.$nextTick(() => { 
    //     this.$refs.table.refresh()
    //   })
    // },
    search() {  
      this.clickShowNav = false 
      this.loadData = (parameter) => { 
        this.queryParam.current = parameter.pageNum
        this.queryParam.pageNum = parameter.pageNum
        this.queryParam.pageSize = parameter.pageSize
        
        return getProductList(Object.assign(this.queryParam, parameter)).then(res => {
          return res 
        }) 
      }
      this.$nextTick(() => {  
        this.$refs.table.refresh(true)
      })
    },
    recursionFindObj(data) {
      if (!data) return
      for (let i in data) {
        if (data.sub && data.sub.length > 0) {
          data.children = data.sub
          data.children.forEach((item) => {
            return this.recursionFindObj(item)
          })
        }
      }
      return data
    },
    async getDB() {
      const res = await getProduct()
      if (res.data && res.data.length > 0) {
        this.treeLoading = false
        res.data.forEach((item) => {
          this.recursionFindObj(item)
        })
      }
      this.treeData = res.data
    },
    changeChild(data) {
      return (data.children = data.sub)
    },
    /**
     * 新增类别
     */
    addClass() {
      this.modal_type = 'add'
      console.log('产品新增')
      this.$refs.addClass.add()
    },
    /**
     * 编辑类别
     */
    editClass() {
      this.modal_type = 'edit'
      this.$refs.addClass.add()
    },
    onContextMenuClick(treeKey, menuKey) {
      console.log(`treeKey: ${treeKey}, menuKey: ${menuKey}`)
    },
    /**
     * 删除类别
     */
    deleteClass() {
      console.log('删除')
    },
    /**
     * 新增项目
     */
    addProject() {
      this.modal_type = 'add'
      console.log('项目')
      this.$refs.addProject.add()
    },
    /**
     * 编辑项目
     */
    editProject(record) {
      this.modal_type = 'edit'
      this.current_row_record = record

      this.$refs.addProject.add()
    },
    /**
     *
     * 复制项目
     *
     */
    copyProject(recoder) {
      console.log('产品管理复制')
    },

    sexFilter(sex) {
      const values = this.sexDictTypeDropDown.filter((item) => item.code == sex)
      if (values.length > 0) {
        return values[0].value
      }
    },
    statusFilter(status) {
      const values = this.statusDictTypeDropDown.filter((item) => item.code == status)
      if (values.length > 0) {
        return values[0].value
      }
    },
    /**
     * 获取字典数据
     */
    sysDictTypeDropDown(text) {
      sysDictTypeDropDown({ code: 'sex' }).then((res) => {
        this.sexDictTypeDropDown = res.data
      })
      sysDictTypeDropDown({ code: 'common_status' }).then((res) => {
        this.statusDictTypeDropDown = res.data
      })
    },
    /**
     * 修改用户状态
     */
    editUserStatus(code, record) {
      // eslint-disable-next-line no-unused-vars
      const status = 0
      // eslint-disable-next-line eqeqeq
      if (code == 0) {
        this.status = 1
        // eslint-disable-next-line eqeqeq
      } else if (code == 1) {
        this.status = 0
      }
      sysUserChangeStatus({ id: record.id, status: this.status }).then((res) => {
        if (res.success) {
          this.$message.success('操作成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error('操作失败：' + res.message)
        }
      })
    },

    /**
     * 单个删除
     */
    singleDelete(record) {
      const param = [{ id: record.id }]
      this.sysUserDelete(param)
    },
    /**
     * 批量删除
     */
    batchDelete() {
      const paramIds = this.selectedRowKeys.map((d) => {
        return { id: d }
      })
      this.sysUserDelete(paramIds)
    },
    /**
     * 批量导出
     */
    batchExport() {
      sysUserExport().then((res) => {
        this.$refs.batchExport.downloadfile(res)
      })
    },
    /**
     * 点击左侧树形菜单查询列表
     */ 
    handleClick(e,num) { 
      if (e.length == 0) {
        return
      }
      
      this.clickShowNav = true
      this.loadData = (parameter) => {
        if(num == 'one'){
          this.queryParam = {
            id: e.toString(),
            pageNum: 1,
            pageSize: 20,
            current: 1
          }
        }else{ 
          this.queryParam = {
            id: e.toString(),
            current: parameter.pageNum,
            pageNum: parameter.pageNum,
            pageSize: parameter.pageSize
          }
           
        }  
        return getItemDetailById(Object.assign(this.queryParam, parameter)).then((res) => {  
          return res 
        })
      }
      
      this.$nextTick(() => {
        this.$refs.table.refresh(true)
      })
       
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
  },
}
</script>
<style lang="less">
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
/deep/ .ant-card-body {
  padding: 0;
}

</style>
